import React, { Component } from 'react';
import { observer, inject } from 'mobx-react';
import { withRouter, Route, Prompt } from 'react-router-dom';
import CustomerViewAndEditStore from '../../stores/form/CustomerViewAndEditStore'
import ChangePosition from '../card/CustomerMap/changePosition'
import CrmResult from '../card/CrmResult'

import { Form, RouteLayout, TabPage, MapPage } from 'weaver-mobile-page';
import { Card, Icon, ActionSheet, ActivityIndicator, Tools, Modal, List } from 'weaver-mobile';
const getCurrentPosition = MapPage.getCurrentPosition;
const ButtonGroup = RouteLayout.ButtonGroup;
const getLabel = Tools.getLabel;
const alert = Modal.alert;
const isIPhone = new RegExp('\\biPhone\\b|\\biPod\\b', 'i').test(window.navigator.userAgent);
let wrapProps;
if (isIPhone) {
    wrapProps = {
        onTouchStart: e => e.preventDefault(),
    };
}

@withRouter
@observer
export default class CustomerViewAndEdit extends Component {
    constructor(props) {
        super(props);
        this.state = {
            store: new CustomerViewAndEditStore(),
            customerId: props.params.id,
            canEdit: props.params.canEdit,
 			isManager: props.params.isManager,
            span: [7, 1],
            selected: "",
            visible: false,
            tabs: [
                { title: props.params.name },
            ],
            popoverProps: {
                onSelect: this.handleSelect,
                onVisibleChange: this.handleVisibleChange,
            },
            tabProps: {
                swipeable: true,
                onChange: (tab) => {
                }
            }
        }
    }
    componentWillMount() {
        const { DoNew } = this.state.store;
        const initParams = this.props.params;
        DoNew(initParams, this);
    }

    componentDidMount() {
        const store = this.state.store;
        store.doInit();
    }

    render() {
        const { viewForm, editForm, isFormInit, buttonProps, isViewForm, isEditForm, getViewForm, cancelEdit, doSave, changeLocalLayout, showMap, lat, lng,initSuccessed ,initFailedMsg} = this.state.store;
        const { span, visible, selected, btns, popoverProps, tabs, tabProps, canEdit } = this.state;
        //按钮组
        let buttonGroupData = [];
        buttonGroupData.push({
            key: 'clear',
            text: getLabel('201', '取消'),
            onClick: () => alert('', getLabel('390915', '确定要离开吗?'), [
                {
                    text: getLabel('201', '取消'),
                    onPress: () => { }
                },
                {
                    text: getLabel('83446', '确定'),
                    onPress: () => cancelEdit()
                },
            ])
        });
        buttonGroupData.push({
            key: 'submit',
            text: getLabel('615', '提交'),
            onClick: () => doSave(),
            type: 'primary',
            disabled: buttonProps.disabled,
            loading: buttonProps.loading
        });
        if (isFormInit) {
            if (initSuccessed) {
                if (isViewForm) {
                    let btns = [];
                    if (canEdit) {
                        btns = [
                            <Icon type="ellipsis" onClick={this.moreClick} />,
                        ];
                    }
                    return (
                        <div >
                            <TabPage
                                className="tab-page-example"
                                btns={btns}
                                span={span}
                                tabs={tabs}
                                tabProps={tabProps}
                                defaultTabBarProps={{ page: 4 }}
                                popover={false}
                                popoverProps={popoverProps}
                            />
                            <div>
                                <Form store={viewForm} className="crm_Form" />
                            </div>
                        </div>
                    );
                } else if (isEditForm) {
                    return (
                        <div>
                            <Route
                                key={changeLocalLayout.id}
                                path={changeLocalLayout.path}
                                render={() => {
                                    // 修改定位
                                    return (
                                        <RouteLayout getContainer={() => document.getElementById("root")}>
                                            <div
                                                key="changeLocalLayout"
                                                className="wm-route-layout"
                                            >
                                                {showMap ?
                                                    <ChangePosition
                                                        lat1={lat}
                                                        lng1={lng}
                                                        onSubmit={this.getLocation}
                                                    /> :
                                                    <div className="crm-bg-loading"><ActivityIndicator text={getLabel('385766', '定位中') + "..."} /></div>
                                                }
                                            </div>
                                        </RouteLayout>
                                    )
                                }}
                            />
                            <div className={"crm-form-main"}>
                                <div className="crm-form-content">
                                    <Form style={{ height: '100%' }} >
                                        <List>
                                            {this.getFields()}
                                        </List>
                                    </Form>
                                </div>
                                <ButtonGroup data={buttonGroupData} />
                            </div>
                        </div>
                    );
                }
            } else {
                return (
                   
                    <div>
                        <CrmResult
                            message={initFailedMsg}
                        />
                    </div>);
            }
        } else {
            return (
                <div className="crm-bg-loading"><ActivityIndicator text={"Loading..."} /></div>
            );
        }
    }
    moreClick = () => {
        const { getEditForm, doDelete } = this.state.store;
        const buttons = [//删除客户和编辑客户只有有编辑权限的人才能操作，查看权限打开后只有一个取消按钮，所以将权限判断放在【...】上
            {
                content: getLabel('501293', '编辑客户'),
            },

        ];
        if (this.state.isManager) {
            buttons.push({ content: getLabel('501292', '删除客户'), });
        }

        buttons.push({ content: getLabel('201', '取消'), });
        ActionSheet.showActionSheetWithOptions({
            options: buttons,
            cancelButtonIndex: buttons.length - 1,
            maskClosable: true,
            'data-seed': 'logId',
            wrapProps,
        }, (buttonIndex) => {
            if (buttonIndex === 0) {
                getEditForm();
            }
			if (this.state.isManager) {
				if (buttonIndex === 1) {
					// 删除联系人
					alert('', getLabel('83600', '您确认要删除吗？'), [
						{ text: getLabel('201', '取消'), onPress: () => { } },
						{
							text: getLabel('83446', '确定'),
							onPress: () => {
								doDelete();
							}
						},
					]);
				}
			}
		}
        )
    }
    changeHandle = (condition, value) => {
        const { editForm, setAddressInfo } = this.state.store;
        const { domkey } = condition;

        editForm.onChange(condition, value);
        setAddressInfo(domkey[0], value);
    }
    getFields = () => {
        const { editForm } = this.state.store;
        const { conditioninfo, isInit } = editForm;
        const groups = [];

        if (isInit) {
            conditioninfo.forEach((group) => {
                const fields = [];
                group.items.forEach((field) => {
                    if (field.domkey[0] !== 'position') {
                        fields.push(<Form.Item
                            key={field.domkey.join('__')}
                            form={editForm}
                            fieldConfig={field}
                            onChange={(condition, value) => {
                                this.changeHandle(condition, value);
                            }}
                            extra={field.domkey[0] === 'address1' ? <div style={{ color: '#55B1F9', marginLeft: '22px', height: '20px' }} onClick={(e) => this.openMap(e)}><span>{getLabel('500934', '选择定位')}</span></div> : ''}
                        />);
                    }
                });
                fields && groups.push(
                    // 分组
                    <div className='wm-form-group' key={group.title}>
                        <div className='wm-form-title' onClick={() => this.handldTogggle(group.title, !group.show)}>
                            {group.title}
                            <Icon className="am-icon" type={group.show ? 'up' : 'down'} />
                        </div>
                        <div className={`wm-form-list-wrap ${group.show ? 'show' : 'hide'}`}>
                            {fields}
                        </div>
                    </div>
                )
            });
        }
        return groups;
    }
    openMap = () => {
        const { changeLocalLayout, getCurrentPosition1, hasPosition } = this.state.store;
        this.props.history.push(changeLocalLayout.path);
        if (!hasPosition) {
            getCurrentPosition().then((result) => {
                getCurrentPosition1(result);
            });
        }
    }
    getLocation = (data) => {
        const { getLocation } = this.state.store;
        getLocation(data);
        this.props.history.go(-1);
    }
    handldTogggle = (...arg) => {
        const { groupToggle } = this.state.store;
        groupToggle(...arg);
    }

    componentWillUnmount = () => {
        window.crmCard&&window.crmCard.doInit();
    }
}